<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/shoppingCar.css">
    <script src="../js/cookie.js"></script>
    <script src="../js/jquery-1.10.1.min.js"></script>
    <script src="../js/api.js"></script>
    <style>
        .box{
            font-size: 18px;
        }
    </style>
</head>
<body>
    <div class="box">
        
    </div>
    <div class="catbox">
        <table id="cartTable">
            <thead>
                <tr>
                    <th><label>
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选</label></th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                
            </tbody>
        </table>
        <div class="foot" id="foot">
            <a class="fl" id="deleteAll" href="javascript:;">删除</a>
            <div class="fr closing" onclick="getTotal();">结 算</div>
            <input type="hidden" id="cartTotalPrice" />
            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件<span
                    class="arrow up">︽</span><span class="arrow down">︾</span></div>
            <div class="selected-view">
                <div id="selectedViewList" class="clearfix">
                    <div><img src="../images/jpg/pic_15.jpg"><span>取消选择</span></div>
                </div>
                <span class="arrow">◆<span>◆</span></span>
            </div>
        </div>
    </div>
</body>
<script>
    var cookie = document.cookie;
    if (cookie) {  // 标识用户身份
        var user = getCookie("lgc");
        if (user) {
            $(".box").html(`欢迎您,${user} <button onclick="exit()">退出</button>`);

            (async function () {
                let result = await searchShoppingByUser({ user });
                console.log(result);
                let { status, list } = result;
                if (status) {
                    var html = "";
                    list.forEach(({ id, goodsId, goodsName, goodsPrice, goodsImg, buyNum }) => {
                        html += `<tr data-id="${id}">
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="${goodsImg}" alt="" /><span>${goodsName}</span></td>
                    <td class="price">${goodsPrice}</td>
                    <td class="count"><span class="reduce">${buyNum>1?"-":""}</span>
                        <input class="count-input" type="text" value="${buyNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${(buyNum * goodsPrice).toFixed(2)}</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>`
                    })

                    $("tbody").html(html);
                }


            })()

        } else {
            location.href = "./login.html?returnUrl=" + encodeURIComponent(location.href);
        }
    }

    $(document).on("click", ".delete", async function () {
        if(confirm("是否删除?")){
            var id = $(this).parents("tr").attr("data-id");
            var result = await deleteShoppingCarById({ id });
            console.log(result);
            var { status } = result;
            if (status) {
                $(this).parents("tr").remove();
            }
        }
    })

    $(document).on("click",".check-all",function(){
        var status = $(this).prop("checked");
        console.log(status);
        $(".check-one").prop("checked",status);
        getTotal();
    })

    $(document).on("click",".check-one",function(){
        if ($(".check-one").length > 0 && $(".check-one:checked").length === $(".check-one").length) {
            $(".check-all").prop("checked", true);
        } else {
            $(".check-all").prop("checked", false);
        }
        getTotal();
    })

    $(document).on("click",".add",function(){
        var num = $(this).prev().val();
        num++;
        $(this).prev().val(num);
        var price = $(this).parent().prev().text();
        var subTotal = (price * num).toFixed(2);
        $(this).parent().next().text(subTotal);
        $(this).prevAll(".reduce").text("-");
        var id = $(this).parents("tr").attr("data-id");
        (async function () {
                let result = await addNum({ id });
                console.log(result);
            })()
        getTotal();
    })

    $(document).on("click",".reduce",function(){
        var num = $(this).next().val();
        var id = $(this).parents("tr").attr("data-id");
        (async function () {
                let result = await reduceNum({ id,num });
                console.log(result);
        })();
        if(num<=2){
            num = 1;
            $(this).text("");
        }else{
            num--;
        }
        $(this).next().val(num);
        var price = $(this).parent().prev().text();
        var subTotal = (price * num).toFixed(2);
        $(this).parent().next().text(subTotal);
        getTotal();
    })

    $(document).on("click",".delete",function(){
        $(this).parents("tr").remove();
        isAllChecked();
        getTotal();
    })

    $(document).on("click","#deleteAll",async function(){
        var list = $(".check-one:checked").parents("tr").map(function () {
            return $(this).attr("data-id");
        }).get();
        console.log(list);
        var str = list.join(",");
        var id = $(this).parents("tr").attr("data-id");
        var result = await deleteShoppingCarById({ id:str });
        console.log(result);
        var { status } = result;
        if (status) {
            $(".check-one:checked").parents("tr").remove();
        }

        isAllChecked();
        getTotal();
    })

    function isAllChecked() {
        if ($(".check-one").length > 0 && $(".check-one:checked").length === $(".check-one").length) {
            $(".check-all").prop("checked", true);
        } else {
            $(".check-all").prop("checked", false);
        }
    }

    function getTotal() {
        var sum = 0;
        var allPrice = 0
        $(".check-one:checked").each(function () {
            var num = $(this).parents("tr").find(".count-input").val() * 1;
            var subTotal = $(this).parents("tr").find(".subtotal").text() * 1
            sum += num;
            allPrice += subTotal;
        })
        $("#selectedTotal").text(sum)
        $("#priceTotal").text(allPrice.toFixed(2));
    }

    function exit() {
        delCookie("lgc");
        location.reload();
    }

</script>
</html>